<template>
  <div
    id="center"
    ref="fullscreenContainer"
    :class="{ fullscreen: isFullscreen }"
  >
    <div class="bg-color-black">
      <div class="controls">
        <button @click="back" class="close-back">返回</button>
        <button @click="toggleFullScreen" class="fullscreen-btn">
          {{ isFullscreen? "⨉" : "⛶" }}
        </button>
      </div>
      <div id="mapChart"></div>
      <div v-if="isLoading" class="loading-overlay">
        <div class="spinner"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import screenfull from "screenfull";
import nameMap from '../assets/json/nameMap.json';
import provinces from '../assets/json/provinces.json';
import provincesText from '../assets/json/provincesText.json';
import {mapActions} from "vuex";


const borderColor = "#e6e8ed";
const chinaColor = "#7fa0dd";
const worldColor = "#58a8d2";
const hoverColor = "rgba(109, 116, 172)";
const textColor = "#243a4e";


export default {
  name: "CenterWithMap",
  data() {
    return {
      isFullscreen: false,
      isLoading: false,
      myChart: null,
      riskData: [],
      userData: {
        id: null,
        username: null,
        email: null,
        role: null
      }
    };
  },
  mounted() {
    this.userData.id = this.$store.state.user.userInfo.id;
    // this.userData.username = this.$store.state.user.userInfo.username;
    // this.userData.email = this.$store.state.user.userInfo.email;
    // this.userData.role = this.$store.state.user.userInfo.role;
    this.initMap();
    window.addEventListener("resize", this.handleResize);
    if (screenfull.isEnabled) {
      screenfull.on("change", this.updateFullscreenState);
    }
    setTimeout(() => {
      const rect = document.getElementById("mapChart").getBoundingClientRect();
      console.log("初始 mapChart 尺寸", rect);
    }, 500);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    if (screenfull.isEnabled) {
      screenfull.off("change", this.updateFullscreenState);
    }
  },
  methods: {
    ...mapActions(['companyDistribution']),
    toggleFullScreen() {
      if (screenfull.isEnabled) {
        this.isLoading = true;
        screenfull.toggle(this.$refs.fullscreenContainer);
        setTimeout(() => {
          this.isLoading = false;
          requestAnimationFrame(() => {
            this.handleResize();
          });
        }, 1000);
      }
    },
    updateFullscreenState() {
      this.isFullscreen = screenfull.isFullscreen;
      this.isLoading = true;
      setTimeout(() => {
        this.isLoading = false;
        requestAnimationFrame(() => {
          this.handleResize();
        });
      }, 1000);
    },
    back() {
      this.initMap();
      const backBtn = document.querySelector(".close-back");
      if (backBtn) backBtn.style.display = "none";
    },
    async initMap() {
      const chartDom = document.getElementById("mapChart");
      if (!chartDom) return;

      this.myChart = echarts.init(chartDom);
      const backBtn = document.querySelector(".close-back");
      if (backBtn) backBtn.style.display = "none";
      // 通过请求访问
      console.log('请求访问')
      const response = await this.companyDistribution(this.userData.id);
      this.riskData = response.data;
      console.log('riskData', this.riskData);
      const riskData = this.riskData;// 定义风险数据（包含数值映射）

      const drawMap = (name) => {
        const mapJson = name === "world"
          ? require("@/assets/json/world.json")
          : require("@/assets/json/province/" + name + ".json");

        if (!mapJson) {
          console.error("无法加载地图数据:", name);
          return;
        }

        echarts.registerMap(name, mapJson);
        const newCenter = name === "world" ? [80.0, 35.0] : mapJson.center;
        const newZoom = name === "world" ? 3 : 1;

        const option = {
          tooltip: {
            show: true,
            trigger: "item",
            formatter: (params) => {
              const riskItem = riskData.find(d => d.name === params.name);
              return riskItem
                ? `${params.name}<br>风险等级: ${riskItem.riskLevel}<br>公司数量: ${riskItem.companyCount}`
                : params.name;
            },
          },
          visualMap: {
            show: true,
            left: "left",
            top: "bottom",
            text: ["高风险", "低风险"], // 顶部是高风险，底部是低风险（符合数值从低到高的视觉逻辑）
            textStyle: { color: "white" },
            // 按区间划分（对应 0~1 的风险值范围）
            pieces: [
              { min: 0.67, label: "高风险", color: "#FF0000" }, // ≥0.67 高风险（红色）
              { min: 0.33, max: 0.67, label: "中风险", color: "#FFA500" }, // 0.33~0.67 中风险（橙色）
              { max: 0.33, label: "低风险", color: "#00FF00" }, // ≤0.33 低风险（绿色）
            ],
            min: 0, // 对应风险值最小值
            max: 1, // 对应风险值最大值
            calculable: true, // 允许用户拖动调整阈值查看
            realtime: true, // 拖动时实时更新视图
          }
          ,
          geo: {
            show: true,
            map: name,
            zoom: newZoom,
            center: newCenter,
            roam: true,
            label: {
              show: newZoom > 3,
              color: textColor,
              fontSize: 12,
            },
            itemStyle: {
              normal: {
                borderColor,
                areaColor: name === "world" ? worldColor : chinaColor,
              },
              emphasis: {areaColor: hoverColor},
            },
            nameMap,
          },
          series: [
            {
              type: "map",
              map: name,
              geoIndex: 0,
              selectedMode: false,
              // 使用 riskValue 作为可视化数值
              data: riskData.map(d => ({name: d.name, value: d.riskValue})),
            },
          ],
        };

        this.myChart.setOption(option);
        this.myChart.on("georoam", () => {
          const zoomLevel = this.myChart.getOption().geo[0].zoom;
          this.myChart.setOption({
            geo: {label: {show: zoomLevel > 3}}
          });
        });
      };

      // 初始显示世界地图
      let selected = "world";
      drawMap(selected);

      // 点击地图切换省级区域
      this.myChart.on("click", (param) => {
        const backBtn = document.querySelector(".close-back");
        for (let i = 0; i < provincesText.length; i++) {
          if (param.name.includes(provincesText[i])) {
            if (backBtn) backBtn.style.display = "block";
            drawMap(provinces[i]);
            break;
          }
        }
      });
    },
    handleResize() {
      if (this.myChart) {
        this.myChart.resize();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
#center {
  position: relative;
  width: 800px;
  height: 670px;
  margin: 0 auto;
  transition: all 0.3s ease;
}

.fullscreen {
  width: 100vw !important;
  height: 100vh !important;
  margin: 0;
}

.bg-color-black {
  width: 100%;
  height: 100%;
  padding: 5px;
  border-radius: 10px;
  box-sizing: border-box;
  position: relative;
}

.controls {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
  display: flex;
  gap: 10px;
}

.close-back,
.fullscreen-btn {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid #ccc;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 4px;
  font-size: 16px;
}

#mapChart {
  width: 100%;
  height: 100%;
  border-radius: 10px;
  transition: width 0.3s ease, height 0.3s ease;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #0C0F32;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.spinner {
  border: 6px solid #f3f3f3;
  border-top: 6px solid #3498db;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
